// 腾讯云oss
const COS = require("cos-nodejs-sdk-v5");
const cos = new COS({
  SecretId: "AKID97qLcfl0JL8fy3uWv62jGZeU5S5WalbC",
  SecretKey: "VCgv1sUs11mKdhX8VeicHitqZ5PVMzOY",
});
const Bucket = "duxinggj-1251133427";
const Region = "ap-guangzhou";
const allowPrefix = "_ALLOW_DIR_/*";
const Pictureprefix =
  "https://duxinggj-1251133427.cos.ap-guangzhou.myqcloud.com/";

/**
 * 上传字节文件到服务器
 *  * @param {*} Body 字节流文件
 * @param typeName 存储文件的目录

 */
exports.upbuff = (Body, typeName, gs, zdyfileName, onProgress) => {
  return new Promise((resolve, reject) => {
    const fileName = randomString(16) + new Date().getTime() + gs;
    let key = "dxgjAdmin/" + typeName + "/" + fileName;
    if (zdyfileName) {
      key = "dxgjAdmin/" + zdyfileName;
    }
    cos.putObject(
      {
        Bucket,
        Region,
        Key: key,
        Body /* 必须 */,
        onProgress: function (progressData) {
          try {
            onProgress(progressData);
          } catch (e) {}
        },
      },

      function (err, data) {
        resolve("https://" + data.Location);
      }
    );
  });
};

/**
 * 上传图片到腾讯云表单形式
 * @param {*} file 接收表单的内容
 * @param {*} typeName 目录文件
 * @returns
 */
exports.upimgFile = (file, typeName, onProgress) => {
  return new Promise((resolve, reject) => {
    const fileName = file.name.split(".")[0] + new Date().getTime();
    const Key =
      "dxgjAdmin/" + typeName + "/" + fileName + "." + file.name.split(".")[1];
    cos.sliceUploadFile(
      {
        Bucket,
        Region,
        Key,
        FilePath: file.path,
        onProgress: function (progressData) {
          try {
            onProgress(JSON.stringify(progressData));
          } catch (e) {}
        },
      },
      function (err, data) {
        resolve({
          imgurl: "https://" + data.Location,
          fileName,
          Key,
        });
      }
    );
  });
};
exports.upwavFile = (file, typeName, onProgress) => {
  return new Promise((resolve, reject) => {
    const fileName = file.name.split(".")[0] + new Date().getTime();
    const Key = "dxgjAdmin/" + typeName + "/" + fileName + ".wav";
    cos.sliceUploadFile(
      {
        Bucket,
        Region,
        Key,
        FilePath: file.path,
        onProgress: function (progressData) {
          try {
            onProgress(JSON.stringify(progressData));
          } catch (e) {}
        },
      },
      function (err, data) {
        resolve({
          imgurl: "https://" + data.Location,
          fileName,
          Key,
        });
      }
    );
  });
};

exports.upluyingFile = (file, typeName, onProgress) => {
  return new Promise((resolve, reject) => {
    const fileName = file.name.split(".")[0] + new Date().getTime();
    const Key = "dxgjAdmin/" + typeName + "/" + fileName + ".aac";

    cos.sliceUploadFile(
      {
        Bucket,
        Region,
        Key,
        FilePath: file.path,
        onProgress: function (progressData) {
          try {
            onProgress(JSON.stringify(progressData));
          } catch (e) {}
        },
      },
      function (err, data) {
        resolve({
          imgurl: "https://" + data.Location,
          fileName,
          Key,
        });
      }
    );
  });
};

/**
 *获取媒体截图
 * @param {*} Key  #媒体路径  如"dxgjAdmin/视频上传/用循环画正方形1662090204767.mp4"
 * @param time 截图的时间点
 * @returns
 */
exports.videojt = (Key, time) => {
  return new Promise((resolve, reject) => {
    cos.request(
      {
        Bucket,
        Region,
        Method: "GET",
        Key,
        Query: {
          "ci-process": "snapshot" /** 固定值，必须 */,
          time: time || 5 /** 截图的时间点，单位为秒，必须 */,
        },
        RawBody: true,
      },
      function (err, data) {
        if (data) {
          let res = data.Body;
          resolve(res);
        } else {
          resolve(false);
        }
      }
    );
  });
};

exports.getImgUrlhenan = (Prefix) => {
  return new Promise((resolve, reject) => {
    cos.getBucket(
      {
        Bucket,
        Region,
        Prefix: "dxgjAdmin/" + Prefix,
      },
      function (err, data) {
        resolve(data.Contents);
      }
    );
  });
};
/**
 * 获取图片列表
 * @param {*} Prefix  目录名称
 * @returns
 */

exports.getImgUrl = (Prefix) => {
  return new Promise((resolve, reject) => {
    cos.getBucket(
      {
        Bucket,
        Region,
        Prefix: "dxgjAdmin/" + Prefix,
      },
      function (err, data) {
        let imgArray = [];
        data.Contents.map((a) => {
          const obj = {};
          let urlser = Pictureprefix + a.Key;
          if (
            a.Key.indexOf("mp4") < 0 &&
            a.Key.indexOf("ofd") < 0 &&
            a.Key.indexOf("m4v") < 0
          ) {
            urlser = urlser + "?imageMogr2/format/webp";
          }
          obj.cover =
            Pictureprefix + a.Key + "?imageMogr2/cut/600x600/gravity/center"; // 缩放裁剪
          obj.blur = Pictureprefix + a.Key + "?imageMogr2/blur/8x5"; // 图片模糊

          obj.url = urlser;
          obj.key = a.Key;
          obj.LastModified = a.LastModified;
          if (a.Key.indexOf("mp4") >= 0) {
            obj.imgurl =
              Pictureprefix +
              a.Key.replace(Prefix, "videojt/" + Prefix).replace("mp4", "jpg");
          }
          if (a.Key.indexOf("m4v") >= 0) {
            obj.imgurl =
              Pictureprefix +
              a.Key.replace(Prefix, "videojt/" + Prefix).replace("m4v", "jpg");
          }

          imgArray.push(obj);
        });

        imgArray = imgArray.sort(function (a, b) {
          //正序a-b
          return new Date(b.LastModified) - new Date(a.LastModified);
        });
        resolve(imgArray);
      }
    );
  });
};

/**
 * 删除图片
 * @param {*} Key
 * @returns
 */
exports.deleteObject = (Key) => {
  return new Promise((resolve, reject) => {
    cos.deleteObject(
      {
        Bucket,
        Region,
        Key,
      },
      function (err, data) {
        resolve(err || data);
      }
    );
  });
};

const randomString = (len) => {
  len = len || 32;
  var $chars =
    "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = "";
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
};

/**
 * 图片识别
 * @param {*} url
 * @returns
 */

exports.imgOCR = (url) => {
  return new Promise((resolve, reject) => {
    cos.request(
      {
        Method: "GET",
        Key: url.split("myqcloud.com/")[1],
        Url: url,
        Query: {
          "ci-process": "OCR",
        },
      },
      function (err, data) {
        console.log(err);
        console.log(data);
        console.log("666");
        if (data) {
          let res = data.Response.TextDetections;
          resolve(res);
        } else {
          resolve(false);
        }
      }
    );
  });
};

/**
 * 身份证识别
 * @param {*} url   'https://duxinggj-1251133427.cos.ap-guangzhou.myqcloud.com/dxgjAdmin/sfz.jpg'
 * @returns
 */

exports.IDCardOCR = (url) => {
  return new Promise((resolve, reject) => {
    cos.request(
      {
        Method: "GET",
        Key: url.split("myqcloud.com/")[1],
        Url: url,
        Query: {
          "ci-process": "IDCardOCR",
        },
      },
      function (err, data) {
        if (data) {
          let res = data.Response.IdInfo;
          resolve(res);
        } else {
          resolve(false);
        }
      }
    );
  });
};

/**
 *
 * 身份证识别
 * @param {*} url   'https://duxinggj-1251133427.cos.ap-guangzhou.myqcloud.com/dxgjAdmin/sfz.jpg'
 * @returns
 */

exports.renlian = (url) => {
  return new Promise((resolve, reject) => {
    cos.request(
      {
        Method: "GET",
        Key: url.split("myqcloud.com/")[1],
        Url: url,
        Query: {
          "ci-process": "AnalyzeFace",
        },
      },
      function (err, data) {
        if (data) {
          let res = data;
          resolve(res);
        } else {
          resolve(err);
        }
      }
    );
  });
};
